/**
 * Copyright (c) 2011-9-23 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.wkm.definition;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wkm.frame.MessageBox;
import org.wkm.task.file.DataReader;

/**
 * The class note
 * @version 1.0 2012-1-17
 * @author WUKUNMENG
 */
public class SystemTrayUtil implements ActionListener{

	private TrayIcon trayIcon = null;
	
	private MenuItem menu = null;
	
	private MenuItem addRegistry = null;
	
	private MenuItem exit = null;
	
	//系统配置文件
	private static DataReader READER = DataReader.getInstance();
		
	private static Logger logger = LoggerFactory.getLogger(SystemTrayUtil.class);
	
	private Bootup boot = new Bootup();
	
	public void showTray() throws AWTException{
		SystemTray tray = SystemTray.getSystemTray();

		Image image = DataReader.getInstance().getImage(
				MessageBox.DEFAULT_IMAGE_NAME);
		Image resizeImage = image.getScaledInstance((int) tray
				.getTrayIconSize().getWidth(), (int) tray.getTrayIconSize()
				.getHeight(), BufferedImage.SCALE_SMOOTH);
		
		PopupMenu popup = new PopupMenu();
		
		menu = new MenuItem(READER.getProperty("system.tray.main.menu"));
		exit = new MenuItem(READER.getProperty("system.tray.exit"));
		if(boot.isCreateAutoFile()){
			addRegistry = new MenuItem(READER.getProperty("system.tray.auto.start.set"));
		} else {
			addRegistry = new MenuItem(READER.getProperty("system.tray.auto.start"));
		}
		menu.addActionListener(this);
		exit.addActionListener(this);
		addRegistry.addActionListener(this);
		
		popup.add(menu);
		popup.add(addRegistry);
		popup.add(exit);
		
		StringBuffer sb = new StringBuffer();
		sb.append("WKM-定时任务管理器");
		trayIcon = new TrayIcon(resizeImage, sb.toString(), popup);
		tray.add(trayIcon);
		trayIcon.displayMessage("提示信息", "定时工具后台运行！", MessageType.INFO);
	}


	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == exit) {
			System.exit(0);
		} else if (e.getSource() == menu){
			logger.info("测试主菜单。");
		} else if (e.getSource() == addRegistry){
			if(boot.isCreateAutoFile()){
				if(boot.deleteAutoFile()){
					addRegistry.setLabel(READER.getProperty("system.tray.auto.start"));
				}
			} else {
				boot.createQuickStartFile();
				boot.createAutoStart();
				addRegistry.setLabel(READER.getProperty("system.tray.auto.start.set"));
			}
		}
	}
	
}
